import 'dart:io';

import 'package:flutter/material.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:ts_app_dart/consts/index.dart';
import 'package:ts_app_dart/utils/index.dart';
import 'package:ts_app_dart/utils/request.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

class SettingScreen extends StatefulWidget {
  const SettingScreen({Key key}) : super(key: key);

  @override
  _SettingScreenState createState() => _SettingScreenState();
}

class _SettingScreenState extends State<SettingScreen> {
  double progressVal = 0.0;
  String latestVersion;
  static GlobalKey<ScaffoldState> _globalKey = GlobalKey();

  @override
  initState() {
    _globalKey.currentState;
    super.initState();
    HttpUtils.get(LaunchUrls.latestVersionUrl).then((response) {
      setState(() {
        latestVersion = response.data['version'].toString();
      });
    });
  }

  Future<void> _installApk(String file) async {
    // 安装新版本（这部分将依赖于平台）
    if (Platform.isAndroid) {
      await InstallPlugin.install(file);
    } else if (Platform.isIOS) {
      // iOS的安装代码
      Uri url = Uri.parse('https://www.apple.com/app-store');

      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw 'Could not launch $url';
      }
    }
    Navigator.of(context).pop();
  }

  Future<void> _showMyDialog(String file) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('应用更新'),
          content: SingleChildScrollView(
            child: ListBody(
              children: const <Widget>[
                Text('This is a demo alert dialog.'),
                Text('Would you like to approve of this message?'),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                _installApk(file);
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> checkAndDownloadUpdate() async {
    // 获取当前应用的版本信息
    final packageInfo = await PackageInfo.fromPlatform();
    final currentVersion = packageInfo.version;

    // // 检查是否有新版本（通过调用API或其他方式获取最新版本号）
    final response = await HttpUtils.get(LaunchUrls.latestVersionUrl);
    final Directory tempDir = await getTemporaryDirectory();
    final Directory downloadsDir = await getDownloadsDirectory();

    print(response.data['version']);
    print(tempDir.path);
    print(downloadsDir.path);
    print('currentVersion $currentVersion');

    if (5 > 2) {
      // 有新版本，下载新版本的安装包
      // final installationFile = '${tempDir.path}/4.png';
      final installationFile = '${tempDir.path}/app-release.apk';
      void onReceiveProgress(int count, int total) {
        print('======> $count,$total');
        setState(() {
          progressVal = count / total;
        });
        if (count >= total) {
          _showMyDialog(installationFile);
        }
      }

      print('-------------- download');
      HttpUtils.download(
        LaunchUrls.downloadUrl,
        installationFile,
        onReceiveProgress,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    ScaffoldState _state = context.findAncestorStateOfType<ScaffoldState>();

    return Scaffold(
      appBar: AppBar(
        title: Text("设置"),
        leading: IconButton(
          onPressed: () {
            if (_state != null) _state.openDrawer();
          },
          icon: Icon(Icons.menu, size: 24.0),
        ),
      ),
      body: Column(children: [
        Padding(
          padding: EdgeInsets.all(12.0),
          child: Container(
            child: Text('SettingScreen'),
          ),
        ),
        Padding(
          padding: EdgeInsets.all(12.0),
          child: Container(
            child: Text(latestVersion ?? 'version'),
          ),
        ),
        Center(
          child: ElevatedButton(
            child: Text('检查更新'),
            onPressed: () {
              checkAndDownloadUpdate();
              // RestartWidget.restartApp(context);
            },
          ),
        ),
        Center(
          child: ElevatedButton(
            child: Text('退出应用'),
            onPressed: () {
              CommonUtils.exitApp(context);
            },
          ),
        ),
        Container(
          child: Padding(
            child: LinearProgressIndicator(
              value: progressVal,
              // backgroundColor: Colors.grey,
            ),
            padding: EdgeInsets.all(20.0),
          ),
        ),
      ]),
    );
  }
}
